package com.piece.mall.service;

import com.piece.core.framework.enums.sql.SqlKey;
import com.piece.core.framework.support.bootstrap.Order;
import com.piece.core.framework.util.collection.CollectionUtil;
import com.piece.core.framework.util.collection.MapUtil;
import com.piece.core.framework.util.time.DateUtil;
import com.piece.core.jpa.repository.BaseService;
import com.piece.mall.model.SmsSeckillSession;
import com.piece.mall.model.SmsSeckillSkuRelation;
import com.piece.mall.repository.SmsSeckillSessionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class SmsSeckillSessionService extends BaseService<SmsSeckillSession, String> {

    @Autowired
    private SmsSeckillSessionRepository smsSeckillSessionRepository;

    @Resource
    private SmsSeckillSkuRelationService smsSeckillSkuRelationService;

    @PostConstruct
    public void initRepository() {
        setRepository(smsSeckillSessionRepository);
    }

    /**
     * 获取最近指定天数的秒杀场次和商品信息
     */
    public List<SmsSeckillSession> getSessionWithinDay(int days) {
        Date startTime = DateUtil.setStartDay(Calendar.getInstance()).getTime();
        Calendar end = new Calendar.Builder().setInstant(DateUtil.addDay(startTime, days)).build();
        Date endTime = DateUtil.setEndDay(end).getTime();
        List<SmsSeckillSession> sessions = findByCondition(MapUtil.builder(new HashMap<String, Object>())
                .put("Q_startTime_D_GE", startTime)
                .put("Q_startTime_D_LE", endTime)
                .build(), Arrays.asList(new Order("startTime", SqlKey.ASC)));
        if (CollectionUtil.isNotEmpty(sessions)) {
            // 组合场次id
            List<Long> sessionIds = sessions.stream().map(SmsSeckillSession::getId).collect(Collectors.toList());
            // 关联商品信息
            List<SmsSeckillSkuRelation> relations = smsSeckillSkuRelationService.findByCondition(MapUtil.builder(new HashMap<String, Object>())
                    .put("Q_promotionSessionId_L_IN", sessionIds)
                    .build());
            Map<Long, List<SmsSeckillSkuRelation>> skuMap = relations.stream().collect(Collectors.groupingBy(SmsSeckillSkuRelation::getSessionId));
            sessions.forEach(session -> session.setRelationSkus(skuMap.get(session.getId())));
        }

        return sessions;
    }
}
